package com.kj.tms.common.utils.excel;

import com.kj.tms.common.utils.StringUtil;
import org.apache.poi.ss.usermodel.*;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: etms-1.0.0
 * @Package: com.hongtu.tms.commonutil.excel
 * @ClassName: ImportExcelUtil
 * @Description: [导入excel公共类]
 * @Author: wangmeng
 * @CreateDate: 2018/8/13 14:47
 * @UpdateUser: []
 * @UpdateDate: 2018/8/13 14:47
 * @UpdateRemark: []
 * @Version: 1.0
 * Copyright: 北京宏图天安 Copyright (c) 2018
 */
public class ImportExcelUtil {

    /**
     * 读取excel
     * @param excelStream excel输入流
     * @param sheetNo sheet索引
     * @param startRow 数据起始行
     * @param headList 表头list
     * @param dataTurnMap 数据转换map
     * @return
     * @throws Exception
     */
    public static List<Map> readExcel(InputStream excelStream,int sheetNo,int startRow,List<Map> headList,Map<String,Map> dataTurnMap) throws Exception{
        List<Map> dataList = new ArrayList<>();
        Workbook workbook = WorkbookFactory.create(excelStream);
        Sheet sheet = workbook.getSheetAt(sheetNo);
        int totalRow = sheet.getLastRowNum();
        for (int i = startRow; i <= totalRow; i++) {
            Map dataMap = new HashMap();
            Row row = sheet.getRow(i);
            for (int j = 0;j<headList.size();j++) {
                Map headMap = headList.get(j);
                int excelColumnNo = StringUtil.toInt(headMap.get("EXCELCOLUMNNO"));
                int dataSource = StringUtil.toInt(headMap.get("DATASOURCE"));//数据来源
                String columnName = StringUtil.toString(headMap.get("COLUMNNAME"));
                Cell cell = row.getCell(excelColumnNo);
                cell.setCellType(Cell.CELL_TYPE_STRING);//设置单元格为字符串格式
                String cellValue = cell.getStringCellValue().trim();
                if (dataSource == 1) {//excel读取
                    dataMap.put(columnName, cellValue);
                }else if (dataSource == 2) {//数据映射
                    Map turnMap = dataTurnMap.get(columnName);
                    dataMap.put(columnName, turnMap.get(cellValue));
                }
            }
            dataList.add(dataMap);
        }
        return dataList;
    }
}
